//
//  KINGOAuthViewController.swift
//  肉荣微博
//
//  Created by king on 15/7/30.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit
import SVProgressHUD

class KINGOAuthViewController: UIViewController, UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "用户登录"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Done, target: self, action: "closeLoginController")
        view.backgroundColor = UIColor.whiteColor()
        print(view)
        webView.loadRequest(NSURLRequest(URL: KINGNetworkTools.sharedTools.loadURL()))
        SVProgressHUD.show()
    }
    
    //重写loadView 让控制器直接加载成webView
    override func loadView() {
        view = webView
    }
    
    //懒加载一个webView
    private lazy var webView: UIWebView = {
        let web = UIWebView()
        web.delegate = self
        //web.backgroundColor = UIColor.blueColor()
        return web
    }()
    //MARK: - webView代理方法
    //根据跳转之前的url， 判断是否登录成功，如果成功获取授权码，如果失败什么也不做
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //获取url中的字符串
        let url = request.URL!.absoluteString
        //判断是否有函数的回调，如果没有该干啥干啥去
        if !url.hasPrefix(KINGNetworkTools.sharedTools.callBack) {
            return true
        }
        //获取URL参数部分
        //print(request.URL!.query!)
        if !request.URL!.query!.hasPrefix("error") {
            //获取认证码
            let str = request.URL!.query!.substringFromIndex(advance(request.URL!.query!.startIndex, "code=".characters.count))
            //根据认证码， 获取权限证书
            KINGNetworkTools.sharedTools.getToken(str, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showInfoWithStatus("您的网络不给力，请稍后重试")
                    print("数据获取失败")
                    let when:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * NSEC_PER_SEC))
                    dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
                        self.closeLoginController()
                    })
                    return
                }
                //如果是可选项数据不为nil 则进行字典转模型
                if let data = result {
                    let model = KINGUserAccount(dict: data)
                    model.loadUserIcon() {
                        let when:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * NSEC_PER_SEC))
                        dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
                            SVProgressHUD.dismiss()
                            self.closeLoginController()
                            NSNotificationCenter.defaultCenter().postNotificationName(KINGRootControllerSwitchNSNotification, object: false)
                        })
                    }
                }
            })
            print("授权证书\(str)")
        }
        return false
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        print("加载完成")
        SVProgressHUD.dismiss()
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        print("开始加载")
    }

    //MARK: - 关闭按钮点击响应事件
    func closeLoginController () {
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
